% 文献[1] Efficient Algorithm for Detecting Layered Space-Time Codes 的仿真复现
clear all;
close all;

% 仿真参数设置
Nt = 4;          % 发送天线数
Nr = 4;          % 接收天线数
SNR_dB = 0:2:30; % SNR范围
num_trials = 10000; % Monte Carlo试验次数

% 初始化BER存储
ber_qr = zeros(size(SNR_dB));      % 无排序QR
ber_sorted_qr = zeros(size(SNR_dB)); % 有排序QR
ber_vblast = zeros(size(SNR_dB));    % V-BLAST作为参考

% Monte Carlo仿真
for snr_idx = 1:length(SNR_dB)
    SNR = SNR_dB(snr_idx);
    errors_qr = 0;
    errors_sorted_qr = 0;
    errors_vblast = 0;
    total_bits = 0;
    
    for trial = 1:num_trials
        % 生成MIMO系统
        [y, H, x] = generate_mimo_system(Nt, Nr, SNR);
        
        % 各种检测器
        x_est_qr = qr_detector(y, H);
        x_est_sorted_qr = sorted_qr_detector(y, H);
        x_est_vblast = vblast_detector(y, H, SNR);
        
        % 计算误比特率
        [errors_qr_trial, bits] = count_bit_errors(x, x_est_qr);
        [errors_sorted_qr_trial, ~] = count_bit_errors(x, x_est_sorted_qr);
        [errors_vblast_trial, ~] = count_bit_errors(x, x_est_vblast);
        
        errors_qr = errors_qr + errors_qr_trial;
        errors_sorted_qr = errors_sorted_qr + errors_sorted_qr_trial;
        errors_vblast = errors_vblast + errors_vblast_trial;
        total_bits = total_bits + bits;
    end
    
    % 计算BER
    ber_qr(snr_idx) = errors_qr / total_bits;
    ber_sorted_qr(snr_idx) = errors_sorted_qr / total_bits;
    ber_vblast(snr_idx) = errors_vblast / total_bits;
end

% 绘制性能曲线（匹配文献格式）
figure;
semilogy(SNR_dB, ber_qr, '-o', 'LineWidth', 2, 'DisplayName', 'QR');
hold on;
semilogy(SNR_dB, ber_sorted_qr, '-s', 'LineWidth', 2, 'DisplayName', 'Sorted QR');
semilogy(SNR_dB, ber_vblast, '-^', 'LineWidth', 2, 'DisplayName', 'V-BLAST');
grid on;
xlabel('E_b/N_0 in dB');
ylabel('BER');
legend('show', 'Location', 'southwest');
title('BER Performance of QR-based Detection (n_T = 4, n_R = 4)'); 